package org.lmd.platform.resolve;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.lmd.platform.entity.sys.ReturnObjct;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {
    @Override
    protected ModelAndView doResolveException(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) {
///       String viewName = determineViewName(ex, request);
        response.setCharacterEncoding("UTF-8");
//        if (viewName != null) {// JSP格式返回
            if (!(request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With") != null && request
                    .getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
                // 如果不是异步请求
                // Apply HTTP status code for error views, if specified.
                // Only apply it if we're processing a top-level request.
//                Integer statusCode = determineStatusCode(request, viewName);
//                if (statusCode != null) {
//                    applyStatusCodeIfPossible(request, response, statusCode);
//                }
//                System.out.println("JSP格式返回" + viewName);
                return getModelAndView("", ex, request);
            } else {// JSON格式返回
                try {
                    response.setContentType("application/json;charset=UTF-8");
                    PrintWriter writer = response.getWriter();
                    ReturnObjct returnObjct=ReturnObjct.error(500,ex.getMessage());
                    String json=JSONObject.toJSONString(returnObjct);
                    writer.write(json);
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
//                System.out.println("JSON格式返回" + viewName);
                return null;
            }
//        } else {
//            return null;
//        }
    }
}

